package com.apo1o.cmscore.controller;

import com.apo1o.cmscore.bean.LoginParam;
import com.apo1o.cmscore.bean.User;
import com.apo1o.cmscore.dao.UserDao;
import com.apo1o.cmscore.exception.ServiceException;
import com.apo1o.cmscore.util.JWTUtil;
import com.apo1o.cmscore.util.MD5Util;
import com.apo1o.cmscore.util.Result;
import com.apo1o.cmscore.util.ResultCode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Apo1o.
 * @Date: 2023/11/16-11-16-14:21
 * @Description： com.apo1o.cmscore.controller
 */
@Api(tags = "登录模块")
@RestController
@RequiredArgsConstructor
public class LoginController {
    private final UserDao userDao;
    private final JWTUtil jwtUtil;

    @ApiOperation(value = "登录", notes = "需要提供用户名和密码")
    @PostMapping("login")
    public Result login(@RequestBody LoginParam param){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,param.getUsername())
                .eq(User::getPassword, MD5Util.MD5(param.getPassword()));
        System.out.println( MD5Util.MD5(param.getPassword()));
        //查询校验
        User user = userDao.selectOne(wrapper);
        if (user==null){
            throw  new ServiceException(ResultCode.USER_LOGIN_ERROR);
        }
        //新增token 相关代码
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("username", user.getUsername());
        // 放入isVip不合适，后期充值成功后，用户不会重新登录，token值不变，导致isVip值是错误的
        map.put("isVip", user.getIsVip());
        map.put("roleId", user.getRoleId());
        String token = jwtUtil.generateJwt(map);
        System.out.println("token = " + token);
        return Result.success(token);
        
    }

    @PostMapping("logout")
    public Result logout(){
        return Result.success();
    }

}
